from datetime import datetime
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_user
from app.crud import bill as bill_crud
from app.schemas.bill import BillCreate, BillUpdate, BillList, BillStats

router = APIRouter()

@router.get("/bills", response_model=BillList)
def get_bills(
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user),
    page: int = Query(1, gt=0),
    page_size: int = Query(20, gt=0),
    start_date: Optional[datetime] = None,
    end_date: Optional[datetime] = None
):
    skip = (page - 1) * page_size
    bills = bill_crud.get_bills(
        db, 
        current_user.id,
        skip=skip, 
        limit=page_size,
        start_date=start_date,
        end_date=end_date
    )
    total = bill_crud.get_bills_count(
        db, 
        current_user.id,
        start_date=start_date,
        end_date=end_date
    )
    return {
        "total": total,
        "list": bills
    }

@router.post("/bills")
def create_bill(
    bill: BillCreate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    return bill_crud.create_bill(db, bill, current_user.id)

@router.delete("/bills/{bill_id}")
def delete_bill(
    bill_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    if not bill_crud.delete_bill(db, bill_id, current_user.id):
        raise HTTPException(status_code=404, detail="Bill not found")
    return {"message": "Bill deleted successfully"}

@router.get("/bills/stats", response_model=BillStats)
def get_bill_stats(
    start_date: datetime,
    end_date: datetime,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    return bill_crud.get_bill_stats(db, current_user.id, start_date, end_date) 